package priv.lhy.ecm.basic.util;

import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * author: lihy
 * date: 2019/5/10 11:16
 * description:
 */
public class RedisUtil {

    /**
     * 切换数据库
     * @param redisTemplate
     * @param databaseIndex
     * @return
     */
    public static StringRedisTemplate switchDatabase(StringRedisTemplate redisTemplate, int
            databaseIndex){
        LettuceConnectionFactory factory = (LettuceConnectionFactory)redisTemplate.getConnectionFactory();
        //springboot2.x的redisTemplate默认使用LettuceConnectionFactory，是共享连接的，不能动态切换数据库
        //需要设置连接不共享
        factory.setShareNativeConnection(false);
        factory.setDatabase(databaseIndex);
        redisTemplate.setConnectionFactory(factory);

        //redisTemplate.getConnectionFactory().getConnection().select(databaseIndex);

        return redisTemplate;

    }
}
